package com.base.ui

import android.content.Context
import android.content.DialogInterface
import android.os.Bundle
import android.view.View
import androidx.activity.OnBackPressedCallback
import androidx.fragment.app.activityViewModels
import com.base.constant.What
import com.base.vm.ImViewModel
import com.im.event.DefaultEvent
import com.im.event.post.postEvent
import com.loyal.core.dialog.LoadingDialog
import com.loyal.core.ui.fragment.BasicFragment

abstract class BaseFragment : BasicFragment(), DialogInterface.OnCancelListener {
    protected var executed = false//防止livedata多次回调

    private var progressDialog: LoadingDialog? = null

    open fun enableBackPressedCallback(): Boolean {
        return false
    }

    open fun onBackPressed() {}

    override fun onAttach(context: Context) {
        super.onAttach(context)
        val callback = object : OnBackPressedCallback(enableBackPressedCallback()) {
            override fun handleOnBackPressed() {
                onBackPressed()
            }
        }
        activity?.onBackPressedDispatcher?.addCallback(this, callback)
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        eventCallback()
    }

    protected open fun eventCallback() {
    }

    @JvmOverloads
    fun showLoading(
        message: String?, outsideFlag: Boolean = false,
        cancelFlag: Boolean = true, listener: DialogInterface.OnCancelListener? = null
    ) {
        dismissLoading()
        val context = context ?: return
        if (null == progressDialog) progressDialog = LoadingDialog(context)
        progressDialog?.let {
            it.setCanceledOnTouchOutside(outsideFlag)
            it.setCancelable(cancelFlag)
            it.setOnCancelListener(listener ?: this)
            it.setMessage(replaceText(message))
            it.show()
        }
    }

    fun dismissLoading() {
        progressDialog?.dismiss()
    }

    override fun onCancel(dialog: DialogInterface?) {
    }

    override fun unbind() {
        executed = false
        if (null != progressDialog) progressDialog = null
    }

    protected fun postSnack(message: CharSequence) {
        postEvent(DefaultEvent(What.SNACK_BAR, message))
    }

    protected val imViewModel: ImViewModel by activityViewModels()

    override fun onPause() {
        dismissLoading()
        super.onPause()
        imViewModel.updateStatus(javaClass.hashCode())
    }

    override fun onResume() {
        super.onResume()
        imViewModel.updateStatus(javaClass.hashCode())
    }
}